<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button" onclick="add()">添加</button>
		<table border="1" width="500px">
			<thead>
				<tr>
					<th>大类</th>
					<th>小类</th>
					<th>件数</th>
					<th>单位</th>
					<th>描述</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				
			</tbody>
		</table>
		
		<script type="text/javascript">
			//对象
			//匿名对象
			//对象里面有属性，属性有值。key：value，属性：值
			let arr = [
				{type1:"肉类",type2:"猪肉",count:1,unit:"箱",desc:"无"},
				{type1:"水果",type2:"进口水果",count:1,unit:"箱",desc:"无"},
				{type1:"活动动物",type2:"猴子",count:1,unit:"只",desc:"无"},
				{type1:"杂货",type2:"杂货",count:1,unit:"箱",desc:"111"}
			];
			//获取table对象
			let table = document.getElementsByTagName("table")[0];
			let tbody = table.getElementsByTagName("tbody")[0];
			// console.log(tbody);//打印
			update();

			/* 增 */
			function add(){
				clear();
				arr.push({type1:"水果",type2:"进口水果",count:10,unit:"箱",desc:"无"});
				update();
			}

			/* 清除表格内容 */
			function clear(){
				let trs = tbody.children;
				for(let index in trs){
					tbody.remove(trs[index]);
				}
				tbody = document.createElement("tbody");
				table.appendChild(tbody);
			}
	
			function update(){
				for(let index in arr){
					let item = arr[index];
					// 遍历
					let tr = document.createElement("tr");
					tbody.appendChild(tr);
					let td = document.createElement("td");
					td.innerText = item.type1;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.type2;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.count;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.unit;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.desc;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerHTML=`
						<button>编辑</button>
						<button onclick="del(${index})">删除</button>
					`;
					tr.appendChild(td);
				}
			}
			
			function del(index){
				console.log(index);
				arr.splice(index,1);
				clear();
				update();
			}
		</script>
	</body>
</html>
